<?php
if (!defined('MVC_ROOT_DIR'))  die('Hacking attempt');	

/**
 * 如果系统php版本中不支持json_encode则使用下面的这个
 */
if (!function_exists('json_encode')){
	function json_encode( $data ) {            
    if( is_array($data) || is_object($data) ) { 
        $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) ); 
        
        if( $islist ) { 
            $json = '[' . implode(',', array_map('json_encode', $data) ) . ']'; 
        } else { 
            $items = Array(); 
            foreach( $data as $key => $value ) { 
                $items[] = json_encode("$key") . ':' . json_encode($value); 
            } 
            $json = '{' . implode(',', $items) . '}'; 
        } 
    } elseif( is_string($data) ) { 
        # Escape non-printable or Non-ASCII characters. 
        # I also put the \\ character first, as suggested in comments on the 'addclashes' page. 
        $string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"'; 
        $json    = ''; 
        $len    = strlen($string); 
        # Convert UTF-8 to Hexadecimal Codepoints. 
        for( $i = 0; $i < $len; $i++ ) { 
            
            $char = $string[$i]; 
            $c1 = ord($char); 
            
            # Single byte; 
            if( $c1 <128 ) { 
                $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1); 
                continue; 
            } 
            
            # Double byte 
            $c2 = ord($string[++$i]); 
            if ( ($c1 & 32) === 0 ) { 
                $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128); 
                continue; 
            } 
            
            # Triple 
            $c3 = ord($string[++$i]); 
            if( ($c1 & 16) === 0 ) { 
                $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128)); 
                continue; 
            } 
                
            # Quadruple 
            $c4 = ord($string[++$i]); 
            if( ($c1 & 8 ) === 0 ) { 
                $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1; 
            
                $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3); 
                $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128); 
                $json .= sprintf("\\u%04x\\u%04x", $w1, $w2); 
            } 
        } 
    } else { 
        # int, floats, bools, null 
        $json = strtolower(var_export( $data, true )); 
    } 
    return $json; 
}
}
if ( !function_exists('json_decode') ){
	function json_decode($json)
	{
		$x = '';
	    $comment = false;
	    $out = '$x=';
	  
	    for ($i=0; $i<strlen($json); $i++)
	    {
	        if (!$comment)
	        {
	            if (($json[$i] == '{') || ($json[$i] == '['))       $out .= ' array(';
	            else if (($json[$i] == '}') || ($json[$i] == ']'))   $out .= ')';
	            else if ($json[$i] == ':')    $out .= '=>';
	            else                         $out .= $json[$i];          
	        }
	        else $out .= $json[$i];
	        if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
	    }
	    eval($out . ';');
	    return $x;
	}
}

/**
 * 
 * 错误提示
 * @param String $eno
 * @param String $lang
 * @param String $info
 */
function errors($eno,$lang='zh',$info=null){
	global $errorInfo;	
	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
	<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title></title></head><body style="margin:0px;background:#E1F4F4">';
	echo '<div style="background:#339999;width:100%;color:#ffffff;float:left;height:auto;border-top:5px solid #2B8080;padding-top:5px;font-weight:bold;border-bottom:5px solid #2B8080;">KC-Framework Info:<br>';
	echo '<div style="width:100%;float:left;height:auto;color:#408080;padding-top:5px;font-weight:normal;background:#ffffff;">
	'.@$info.'<br><span style="color:red">'.$errorInfo[$eno].'</span></div><br>';
	echo '</div>';
	echo '</body>
	</html>';
	die();
}

/**
 * 
 * 在模板中调用另外一个模板文件
 * @param String $file 调用顺序1,当前文件夹中，2/app/templates/中
 */
function htmlTemplate($file){
	global $tpl;
	$arr = get_object_vars($tpl);		
	foreach ($arr as $key => $value) {			
		$$key=$value;
	}	
	$act = new Actions();
	$c = $act->getPmoduleName();
	$m = $act->getModuleName();
	$dir1 = MVC_ROOT_DIR.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.$c.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$file;	
	if (file_exists($dir1)){				
		return include $dir1;
	}else{		
		if (file_exists($dir1.'.tpl.php'))	{
			$tpl->template_dir = $dir1.'.tpl.php';
			return include $dir1.'.tpl.php';
		}else{
			$dir2 = MVC_ROOT_DIR.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$file;			
			if (file_exists($dir2)){			
				return include  $dir2;	
			}else{	
				if (file_exists($dir2.'.tpl.php'))	{
					$tpl->template_dir = $dir2.'.tpl.php';
					return include $dir2.'.tpl.php';
				} else {		
					errors('2003','zh',$dir1);
				}
			}
			
		}
	}
	
}
/**
 * 
 * 清除缓存
 */
function clearCache(){
	$cacheFileDir = MVC_CACHE_DIR.'file'.DIRECTORY_SEPARATOR;
	if (is_dir($cacheFileDir)) {
		$dh=opendir($cacheFileDir);//打开目录  //列出目录中的所有文件并去掉 . 和 ..  
		while (false !== ( $file = readdir ($dh))) 
		{			
			if($file!="." && $file!="..") 
			{       
				$fullpath=$cacheFileDir.$file; 					
				if(!is_dir($fullpath)) {  
					unlink($fullpath);					
				}     
			}				
		}						
	}
	
	$cacheFileDir = MVC_CACHE_DIR.'db'.DIRECTORY_SEPARATOR;
	if (is_dir($cacheFileDir)) {
		$dh=opendir($cacheFileDir);//打开目录  //列出目录中的所有文件并去掉 . 和 ..  
		while (false !== ( $file = readdir ($dh))) 
		{			
			if($file!="." && $file!="..") 
			{       
				$fullpath=$cacheFileDir.$file; 					
				if(!is_dir($fullpath)) {  
					unlink($fullpath);					
				}     
			}				
		}						
	}	
}

/**
 * 
 * 通过curl获取URL信息
 * @param String $url
 */
function curlGetContents($url){
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL, $url); 
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 	
	$data = curl_exec($ch); 
	curl_close($ch);
	return $data;
}

/**
 * 通过curl提交数据到指定URL
 * $data = array('name' => 'Dennis', 'surname' => 'Pallett');
 * @param String $url
 * @param Array $data
 */
function curlPostData($url,$data){
	$ch = curl_init(); //初始化	
	curl_setopt($ch, CURLOPT_URL,$url); //设置传输URL		 
	curl_setopt($ch, CURLOPT_POST, true); //设置传输类型为POST
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 提交数据
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//返回数据并不直接打印
	$rs = curl_exec($ch);
	return $rs;
}
/**
 * 
 * 设置session值
 * @param void $key
 * @param void $value
 * @param void $time
 */
function setSession($key,$value,$time=null){
	if (!key_exists($key, $_SESSION)){
		$_SESSION[$key]=$value;
		return true;
	}else{
		return false;
	}
}
/**
 * 
 * 重置session
 * @param void $key
 * @param void $value
 * @param void $time
 */
function resetSession($key,$value,$time=null){
	$_SESSION[$key]=$value;
}
/**
 * 
 * 获取session值
 * @param void $key
 */
function getSession($key){
	return @$_SESSION[$key];
}
function g($key){
	return $_SESSION[$key];
}
function user($key){
	return $_SESSION['user']['userinfo'][$key];
}

function editor($id,$width,$height,$msg=null){
	
	$html ='<link type="text/css" rel="stylesheet" href="'.MVC_WWW_HOST.'js/editor/skins/default.css">';
	$html .= '<script src="'.MVC_WWW_HOST.'/js/editor/kindeditor-min.js" type="text/javascript"></script>';
	
	$html .= "<script>
			KE.show({
				id : '".$id."',
				cssPath : './index.css',
				afterCreate : function(id) {
					KE.event.ctrl(document, 13, function() {
						KE.sync(id);
						document.forms['example'].submit();
					});
					KE.event.ctrl(KE.g[id].iframeDoc, 13, function() {
						KE.sync(id);
						document.forms['example'].submit();
					});
				}
			});
		</script>";
	$html .='<textarea id="'.$id.'" name="'.$id.'" style="width:'.$width.'px;height:'.$height.'px;visibility:hidden;">'.$msg.'</textarea>';
	return $html;
}

$a=0;
function flashUpload($id,$callbackID,$auto='false',$mu='false'){
	global $a;
	$html='';
	$updir = MVC_WEB_DIR."upload/images/".date("Ymd");
	if ($a==0){
	$html ='<link type="text/css" rel="stylesheet" href="'.MVC_WWW_HOST.'js/flashupload/uploadify.css">';
	$html .= '<script src="'.MVC_WWW_HOST.'js/flashupload/swfobject.js" type="text/javascript"></script>';
	$html .= '<script src="'.MVC_WWW_HOST.'js/flashupload/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>';
	}
	$html .='<script type="text/javascript">
	
	';
	
	$a =1;
	$html .= "$(document).ready(function() {";
	if ($mu=='true'){
		$html .=" var mu = true;";
	}else{
		$html .=" var mu = false;";
	}
	$html .= " $('#".$id."').uploadify({
	    'uploader'  : '".MVC_WEB_DIR."js/flashupload/uploadify.swf',
	    'script'    : '".MVC_WEB_DIR."js/flashupload/uploadify.php',
	    'cancelImg' : '".MVC_WEB_DIR."js/flashupload/cancel.png',
	    'folder'    : '".$updir."',
	    'auto'      : $auto,
	    'multi'       : $mu,
	    'onComplete': function(event, ID, fileObj, response, data) {
	    					var lastPath = fileObj.filePath;
	    					lastPath = lastPath.replace('".MVC_WEB_DIR."','');
	    					var newPath = lastPath+'.thumb'+fileObj.type;
	    					
	    					if(mu==true){
	    						var prePath = $('#".$callbackID."').val();
	    						newPath = newPath+';\\n'+prePath;
							}
	    					$('#".$callbackID."').val(newPath);
						}
	  });
	});
	</script>";
	$html .='<div style="width:80px;float:left;padding-left:6px;padding-top:1px;"><input id="'.$id.'" name="'.$id.'" type="file" /></div>';
	if ($auto=='false'){
		$html .='<div style="width:50px;float:left"><input type="button" value="上 传" onclick="$('."'#file_upload'".').uploadifyUpload();"></div>';
	}
	
	return $html;
}

function alert($msg) {
	header('Content-type: text/html; charset=UTF-8');	 
	echo json_encode(array('error' => 1, 'message' => $msg));
	exit;
}


/**
 * 
 * 汉字转换成拼音
 * @param void $key
 */
function pinYin($string, $code='gb2312'){  
        $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".  
                        "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".  
                        "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".  
                        "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".  
                        "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".  
                        "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".  
                        "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".  
                        "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".  
                        "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".  
                        "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".  
                        "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".  
                        "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".  
                        "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".  
                        "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".  
                        "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".  
                        "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";  
        $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".  
                        "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".  
                        "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".  
                        "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".  
                        "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".  
                        "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".  
                        "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".  
                        "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".  
                        "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".  
                        "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".  
                        "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".  
                        "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".  
                        "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".  
                        "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".  
                        "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".  
                        "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".  
                        "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".  
                        "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".  
                        "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".  
                        "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".  
                        "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".  
                        "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".  
                        "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".  
                        "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".  
                        "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".  
                        "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".  
                        "|-10270|-10262|-10260|-10256|-10254";  
        $_TDataKey   = explode('|', $_DataKey);  
        $_TDataValue = explode('|', $_DataValue);
        $_Data = array_combine($_TDataKey,  $_TDataValue);
        arsort($_Data);  
        reset($_Data);
        if($code!= 'gb2312') $string = U2_Utf8_Gb($string);  
        $_Res = '';  
        for($i=0; $i<strlen($string); $i++)  {  
                $_P = ord(substr($string, $i, 1));  
                if($_P>160) { 
                        $_Q = ord(substr($string, ++$i, 1)); $_P = $_P*256 + $_Q - 65536;
                }  
                $_Res .= pinyingChange($_P, $_Data);  
        }  
        return preg_replace("/[^a-z0-9]*/", '', $_Res);  
}  
function pinyingChange($_Num, $_Data){  
        if($_Num>0 && $_Num<160 ){
                return chr($_Num);
        }elseif($_Num<-20319 || $_Num>-10247){
                return '';
        }else{  
                foreach($_Data as $k=>$v){ if($v<=$_Num) break; }  
                return $k;  
        }  
}
function pinYinFirst($zh){
    $zh = str_replace(' ', '', $zh);
    $ret = "";    
    $s1 = @iconv("UTF-8","gb2312", $zh);    
    $s2 = @iconv("gb2312","UTF-8", $s1);    
    if($s2 == $zh){$zh = $s1;}    
    for($i = 0; $i < strlen($zh); $i++){    
        $s1 = substr($zh,$i,1);    
        $p = ord($s1);    
        if($p > 160){    
            $s2 = substr($zh,$i++,2);    
            $ret .= getfirstchar($s2);    
        }else{    
            $ret .= $s1;
        
        }    
    }    
    return $ret;
}
function getfirstchar($s0){  
    $fchar = ord($s0{0});    
    if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});        
    $s1 = @iconv("UTF-8","gb2312", $s0);        
    $s2 = @iconv("gb2312","UTF-8", $s0);        
    if($s2 == $s0){$s = $s1;}else{$s = $s0;}        
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;        
    if($asc >= -20319 and $asc <= -20284) return "A";        
    if($asc >= -20283 and $asc <= -19776) return "B";        
    if($asc >= -19775 and $asc <= -19219) return "C";        
    if($asc >= -19218 and $asc <= -18711) return "D";        
    if($asc >= -18710 and $asc <= -18527) return "E";        
    if($asc >= -18526 and $asc <= -18240) return "F";        
    if($asc >= -18239 and $asc <= -17923) return "G";        
    if($asc >= -17922 and $asc <= -17418) return "H";        
    if($asc >= -17417 and $asc <= -16475) return "J";        
    if($asc >= -16474 and $asc <= -16213) return "K";        
    if($asc >= -16212 and $asc <= -15641) return "L";        
    if($asc >= -15640 and $asc <= -15166) return "M";        
    if($asc >= -15165 and $asc <= -14923) return "N";        
    if($asc >= -14922 and $asc <= -14915) return "O";        
    if($asc >= -14914 and $asc <= -14631) return "P";        
    if($asc >= -14630 and $asc <= -14150) return "Q";        
    if($asc >= -14149 and $asc <= -14091) return "R";        
    if($asc >= -14090 and $asc <= -13319) return "S";        
    if($asc >= -13318 and $asc <= -12839) return "T";        
    if($asc >= -12838 and $asc <= -12557) return "W";        
    if($asc >= -12556 and $asc <= -11848) return "X";        
    if($asc >= -11847 and $asc <= -11056) return "Y";        
    if($asc >= -11055 and $asc <= -10247) return "Z";        
    return null;

}

function U2_Utf8_Gb($_C){  
        $string = '';  
        if($_C < 0x80){
                $string .= $_C;
        }elseif($_C < 0x800)  {  
                $string .= chr(0xC0 | $_C>>6);  
                $string .= chr(0x80 | $_C & 0x3F);  
        }elseif($_C < 0x10000){  
                $string .= chr(0xE0 | $_C>>12);  
                $string .= chr(0x80 | $_C>>6 & 0x3F);  
                $string .= chr(0x80 | $_C & 0x3F);  
        }elseif($_C < 0x200000) {  
                $string .= chr(0xF0 | $_C>>18);  
                $string .= chr(0x80 | $_C>>12 & 0x3F);  
                $string .= chr(0x80 | $_C>>6 & 0x3F);  
                $string .= chr(0x80 | $_C & 0x3F);  
        }  
        return iconv('UTF-8', 'GB2312', $string);  
}
/**
 * 
 * 截取字符串，多余的用...表示
 * @param string $string
 * @param integer $length
 * @param string $etc
 * @param string $code
 */
function truncate($string, $length = 80, $etc = '...', $code = 'UTF-8'){
	if ($length == 0)
        return '';
    if ($code == 'UTF-8') {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    }
    else {
    $pa = "/[\x01-\x7f]|[\xa1-\xff][\xa1-\xff]/";
    }
    preg_match_all($pa, $string, $t_string);
    if (count($t_string[0]) > $length)
        return join('', array_slice($t_string[0], 0, $length)) . $etc;
    return join('', array_slice($t_string[0], 0, $length)) . $etc;
}


function thumb($src)
{
	
	
	if (preg_match('/[-.]gif$/', $src)){
		return str_replace('.thumb.gif','',$src).'.thumb.gif';
	}
	return $src;
}
/**
 * 
 * 按键值排序数组$arr = array=(0=>array("uid"=>2),1=>array("uid"=>1),2=>array("uid"=>3))   array_sort_by_filed($arr,"uid")
 * @param array $arr_data
 * @param string $field
 * @param bool $descending
 */
function array_sort_by_filed($arr_data, $field, $descending = true)
{
	$arrSort = array();
	foreach ( $arr_data as $key => $value ) {
		$arrSort[$key] = $value[$field];
	}
		
	if( $descending ) {
		arsort($arrSort);
	} else {
		asort($arrSort);
	}
	$resultArr = array();
	foreach ($arrSort as $key => $value ) {
		$resultArr[] = $arr_data[$key];
	}
	return $resultArr;
}

/**
 * 
 * 发送socket
 * @param string $server
 * @param string $port
 * @param string $data
 */
function socketData($server, $port, $data) {	
	$commonProtocol = getprotobyname ( 'TCP' );
	$socket = socket_create ( AF_INET, SOCK_STREAM, $commonProtocol );
	socket_set_option ( $socket, SOL_SOCKET, SO_RCVTIMEO, array ("sec" => 1, "usec" => 0 ) );
	socket_connect ( $socket, $server, $port );
	socket_write ( $socket, $data, strlen ( $data ) ); //发送数据
	$out = @socket_read ( $socket, 2018 );		
	socket_close ( $socket );
	return trim ( $out );
}


function echoEditTr($row,$cname,$id,$inputWidth = 300,$type='input',$selectRowKey='',$selectRowValue='',$selectAll='',$selectCompareKey='',$selectCompareVal=''){
    echo '<tr>
    <td align="right"  >'.$cname.'</td>
    <td align="left" >';
    if ($type=='input'){
        if (@$row){            
            echo '<input type="text" style="width:'.$inputWidth.'px;" name="'.$id.'" id="'.$id.'" value="'.$row[$id].'">';         
        }else{           
            echo '<input type="text" style="width:'.$inputWidth.'px;" name="'.$id.'" id="'.$id.'" value="">';            
        }
    }
        
    if ($type=='thumb'){
        echo '<div style="width:410px;float:left;"><input type="text"  name="'.$id.'" id="'.$id.'" style="width:400px;" value="';
        if(@$row) echo $row[$id];
        echo '"/></div>';
        echo flashUpload('file_upload'.$id,$id,'true');
        echo '<div style="width:160px;float:left;"><input type="button" onclick="cutimg('."'".$id."'".')" value=" 编辑图片 " style="height:22px;"/>
        <input type="button" onclick="showSysimg('."'".$id."'".')" value=" 站内图片 "  style="height:22px;"/>
        </div>';
    }
    
    if ($type=='time'){
        echo '<input 
		id="'.$id.'" 
		name="'.$id.'" 
		type="text" 
		style="width:85px;"
		value="';
		if (@$row){
			echo $row[$id];
		}
		echo '" class="date demo_time" ';  
		echo 'onClick="WdatePicker({skin:'."'".'whyGreen'."'".',dateFmt:'."'".'yyyy-MM-dd'."'".'})"
		>';
    }
    if ($type=='select'){
        echo '<select name="'.$id.'" id="'.$id.'" >';
	     
	    if (@$row){
	        echo '<option value="'.$row[$selectRowKey].'">'.$row[$selectRowValue].'</option>';
	    }	   
		foreach ($selectAll as $k=>$v):
		    if ($selectCompareKey){ 
		        if ($row[$selectRowKey]==$v[$selectCompareKey]) continue;
		    }else{
		        if ($row[$selectRowKey]==$v) continue;
		    }
		if ($selectCompareKey) {
		    echo '<option value="'.$v[$selectCompareKey].'">'.$v[$selectCompareVal].'</option>';
		}else{
		    echo '<option value="'.$v.'">'.$v.'</option>';
		}
		endforeach;
		 
	    echo '</select>';
    }
    if ($type=='content'){
        if (@$row){
			$content = $row[$type];	
		}else{
			$content=null;
		}
		echo editor($type,800,300,$content);
    }
    
    echo '
    </td>
    </tr>';
}

function isImg($file){
    $file = strtolower($file);
    $array = array('jpg',
            'jpeg','png','gif','bmp');
    if (str_replace($array, '', $file)!=$file){
        return true;
    }else{
        return false;
    }
}

function isThumb($path){
    $pattern = '/[-.]thumb[-.]/';
    if (preg_match($pattern, $path)){
        return true;
    }else{
        return false;
    }
}
function addAction($c,$m,$a,$n){
    $pathname=MVC_ROOT_DIR.'/app/modules/'.$c.'/'.$m.'/actions/';
    if (!file_exists($pathname)){
        mkdir($pathname,0777,1);
    }
    $fileName=$pathname.'actions.class.php';
    
    if (!file_exists($fileName)){
        file_put_contents($fileName, '<?php
class '.$m.'Actions extends Base'.ucfirst($c).'Actions
{
    public  $'.$m.';
    public function __construct()
    {
        parent::__construct();
    }
    /**
    *
    * '.$n.'首页
    */
    public function actions'.ucfirst($a).'()
    {
        
    }
}#classEnd');
    }else{
        $befFileContents = str_replace('}#classEnd','
    /**
    *
    * '.$n.'
    */
    ',file_get_contents($fileName));
    file_put_contents($fileName,$befFileContents.'public function actions'.ucfirst($a).'()
    {
        
    }
}#classEnd');
    }
    
    $pathname=MVC_ROOT_DIR.'/app/modules/'.$c.'/'.$m.'/templates/';
    if (!file_exists($pathname)){
        mkdir($pathname,0777,1);
    }
    $fileName=$pathname.$a.'.tpl.php';
    
    if (!file_exists($fileName)){
        file_put_contents($fileName, '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>');
    }
}

function getFileName($path){
    preg_match_all('/[\w]+[-.][\w]+$/', $path, $matches);
    return $matches[0][0];
}

function mvcurl($url)
{
    $url = preg_replace('/(\w)\/\//', '${1}/', $url);
    return $url;
}
function getSysInc($key1,$key2=NULL)
{
	global $systemSetting;
	if (!$key2){
		return $systemSetting[$key1];
	}else {
		return $systemSetting[$key1][$key2];
	}
}

function curlRequest($url, $postdata = '', $cockieid = '') {
    
    $ch = curl_init ();
    $option = array (
        CURLOPT_URL => $url, 
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1 
    );
    if ($cockieid) {
        
        $strCookie = 'ssid = ' . $cockieid ; 
        session_write_close();
        $option [CURLOPT_COOKIE] = $strCookie;
              
    }
    if ($postdata) {
        $option [CURLOPT_POST] = 1;
        $option [CURLOPT_POSTFIELDS] = $postdata;
    }
    curl_setopt_array ( $ch, $option );
    $response = curl_exec ( $ch );  
    curl_close ( $ch );    
    //sleep(180);
    return json_decode($response,true);
}
function postFile($post_url,$post_data){
       
	$file_to_upload = $post_data; 
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL,$post_url); 
	curl_setopt($ch, CURLOPT_POST,1); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $file_to_upload); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        
	$result=curl_exec ($ch);         
	curl_close ($ch);        
	return json_decode($result,true); 
}
function random($percent) {  
    $one = rand(1,100);
    $total = range(1,100);
    $tmpRange = array();
    $i=0;
    while ( $i<$percent){
        array_push($tmpRange, $total[$i]);        
        $i+=1;
    }
    foreach ($tmpRange as $v){
        if ($one==$v){
            return true;
        }
    }
    return false;
}